{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d7d1bce-e447-4702-baf5-2bfb8d112635",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp date_features"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "713b6f07-67b5-4fcc-bbd8-5aa3107a4463",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide \n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf0edfb1-a7b3-4d6e-acbd-f41758af1779",
   "metadata": {},
   "source": [
    "# Date Features "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5980c8e1-0416-4e2b-a335-08c7a809916e",
   "metadata": {},
   "source": [
    "Useful classes to generate date features and add them to `TimeGPT`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b22a584a-1591-46bf-860e-20f0a519e7c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "from typing import Dict, List\n",
    "\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5f2f081-c3ff-4ba8-a7d0-b1dc992f5e09",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "from nbdev.showdoc import show_doc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02b6979b-b97a-41eb-9bf1-8e068da1ebcb",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exporti\n",
    "def _transform_dict_holidays(dict_holidays_dates):\n",
    "    dict_holidays = {}\n",
    "    for key, value in dict_holidays_dates.items():\n",
    "        if value not in dict_holidays:\n",
    "            dict_holidays[value] = []\n",
    "        dict_holidays[value].append(key)\n",
    "    return dict_holidays"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d442cd19-c0e3-4aac-a720-07203fef41c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| exporti\n",
    "def _get_holidays_df(dates, categories, holiday_extractor, supported_categories):\n",
    "    years = dates.year.unique().tolist()\n",
    "    total_holidays = dict()\n",
    "    for cat in categories:\n",
    "        if cat not in supported_categories:\n",
    "            raise Exception(f'Holidays for {cat} not available, please remove it.')\n",
    "        dict_holidays = _transform_dict_holidays(holiday_extractor(cat, years=years))\n",
    "        for key, val in dict_holidays.items():\n",
    "            total_holidays[f'{cat}_{key}'] = [int(ds.date() in val) for ds in dates]\n",
    "    return pd.DataFrame(total_holidays, index=dates)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8bedda61-b017-430d-85ce-8a369b8e1bb4",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class CountryHolidays:\n",
    "    \"\"\"Given a list of countries, returns a dataframe with holidays for each country.\"\"\"\n",
    "    \n",
    "    def __init__(self, countries: List[str]):\n",
    "        self.countries = countries\n",
    "    \n",
    "    def __call__(self, dates: pd.DatetimeIndex):\n",
    "        try:\n",
    "            from holidays.utils import country_holidays\n",
    "            from holidays.utils import list_supported_countries\n",
    "        except ModuleNotFoundError:\n",
    "            raise Exception(\n",
    "                'You have to install additional libraries to use holidays, '\n",
    "                'please install them using `pip install \"nixtla[date_extras]\"`'\n",
    "            )\n",
    "        return _get_holidays_df(dates, self.countries, country_holidays, list_supported_countries())\n",
    "    \n",
    "    def __name__(self):\n",
    "        return 'CountryHolidays'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb22ad7a-fc3b-4ce1-aa2e-16f3aaf2c66d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "---\n",
       "\n",
       "#### CountryHolidays\n",
       "\n",
       ">      CountryHolidays (countries:List[str])\n",
       "\n",
       "Given a list of countries, returns a dataframe with holidays for each country."
      ],
      "text/plain": [
       "---\n",
       "\n",
       "#### CountryHolidays\n",
       "\n",
       ">      CountryHolidays (countries:List[str])\n",
       "\n",
       "Given a list of countries, returns a dataframe with holidays for each country."
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "show_doc(CountryHolidays, title_level=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bcc7c4d1-663e-4835-8e95-5ca756cd35ce",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>US_New Year's Day</th>\n",
       "      <th>US_Martin Luther King Jr. Day</th>\n",
       "      <th>US_Washington's Birthday</th>\n",
       "      <th>US_Memorial Day</th>\n",
       "      <th>US_Independence Day</th>\n",
       "      <th>US_Labor Day</th>\n",
       "      <th>US_Columbus Day</th>\n",
       "      <th>US_Veterans Day</th>\n",
       "      <th>US_Veterans Day (Observed)</th>\n",
       "      <th>US_Thanksgiving</th>\n",
       "      <th>...</th>\n",
       "      <th>MX_Día de la Independencia [Independence Day]</th>\n",
       "      <th>MX_Día de la Independencia [Independence Day] (Observed)</th>\n",
       "      <th>MX_Día de la Revolución [Revolution Day] (Observed)</th>\n",
       "      <th>MX_Día de la Revolución [Revolution Day]</th>\n",
       "      <th>MX_Transmisión del Poder Ejecutivo Federal [Change of Federal Government]</th>\n",
       "      <th>MX_Transmisión del Poder Ejecutivo Federal [Change of Federal Government] (Observed)</th>\n",
       "      <th>MX_Navidad [Christmas]</th>\n",
       "      <th>MX_Día de la Constitución [Constitution Day]</th>\n",
       "      <th>MX_Año Nuevo [New Year's Day] (Observed)</th>\n",
       "      <th>MX_Día del Trabajo [Labour Day] (Observed)</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2018-09-03</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-09-04</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-09-05</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-09-06</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-09-07</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>...</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 31 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "            US_New Year's Day  US_Martin Luther King Jr. Day  \\\n",
       "2018-09-03                  0                              0   \n",
       "2018-09-04                  0                              0   \n",
       "2018-09-05                  0                              0   \n",
       "2018-09-06                  0                              0   \n",
       "2018-09-07                  0                              0   \n",
       "\n",
       "            US_Washington's Birthday  US_Memorial Day  US_Independence Day  \\\n",
       "2018-09-03                         0                0                    0   \n",
       "2018-09-04                         0                0                    0   \n",
       "2018-09-05                         0                0                    0   \n",
       "2018-09-06                         0                0                    0   \n",
       "2018-09-07                         0                0                    0   \n",
       "\n",
       "            US_Labor Day  US_Columbus Day  US_Veterans Day  \\\n",
       "2018-09-03             1                0                0   \n",
       "2018-09-04             0                0                0   \n",
       "2018-09-05             0                0                0   \n",
       "2018-09-06             0                0                0   \n",
       "2018-09-07             0                0                0   \n",
       "\n",
       "            US_Veterans Day (Observed)  US_Thanksgiving  ...  \\\n",
       "2018-09-03                           0                0  ...   \n",
       "2018-09-04                           0                0  ...   \n",
       "2018-09-05                           0                0  ...   \n",
       "2018-09-06                           0                0  ...   \n",
       "2018-09-07                           0                0  ...   \n",
       "\n",
       "            MX_Día de la Independencia [Independence Day]  \\\n",
       "2018-09-03                                              0   \n",
       "2018-09-04                                              0   \n",
       "2018-09-05                                              0   \n",
       "2018-09-06                                              0   \n",
       "2018-09-07                                              0   \n",
       "\n",
       "            MX_Día de la Independencia [Independence Day] (Observed)  \\\n",
       "2018-09-03                                                  0          \n",
       "2018-09-04                                                  0          \n",
       "2018-09-05                                                  0          \n",
       "2018-09-06                                                  0          \n",
       "2018-09-07                                                  0          \n",
       "\n",
       "            MX_Día de la Revolución [Revolution Day] (Observed)  \\\n",
       "2018-09-03                                                  0     \n",
       "2018-09-04                                                  0     \n",
       "2018-09-05                                                  0     \n",
       "2018-09-06                                                  0     \n",
       "2018-09-07                                                  0     \n",
       "\n",
       "            MX_Día de la Revolución [Revolution Day]  \\\n",
       "2018-09-03                                         0   \n",
       "2018-09-04                                         0   \n",
       "2018-09-05                                         0   \n",
       "2018-09-06                                         0   \n",
       "2018-09-07                                         0   \n",
       "\n",
       "            MX_Transmisión del Poder Ejecutivo Federal [Change of Federal Government]  \\\n",
       "2018-09-03                                                  0                           \n",
       "2018-09-04                                                  0                           \n",
       "2018-09-05                                                  0                           \n",
       "2018-09-06                                                  0                           \n",
       "2018-09-07                                                  0                           \n",
       "\n",
       "            MX_Transmisión del Poder Ejecutivo Federal [Change of Federal Government] (Observed)  \\\n",
       "2018-09-03                                                  0                                      \n",
       "2018-09-04                                                  0                                      \n",
       "2018-09-05                                                  0                                      \n",
       "2018-09-06                                                  0                                      \n",
       "2018-09-07                                                  0                                      \n",
       "\n",
       "            MX_Navidad [Christmas]  \\\n",
       "2018-09-03                       0   \n",
       "2018-09-04                       0   \n",
       "2018-09-05                       0   \n",
       "2018-09-06                       0   \n",
       "2018-09-07                       0   \n",
       "\n",
       "            MX_Día de la Constitución [Constitution Day]  \\\n",
       "2018-09-03                                             0   \n",
       "2018-09-04                                             0   \n",
       "2018-09-05                                             0   \n",
       "2018-09-06                                             0   \n",
       "2018-09-07                                             0   \n",
       "\n",
       "            MX_Año Nuevo [New Year's Day] (Observed)  \\\n",
       "2018-09-03                                         0   \n",
       "2018-09-04                                         0   \n",
       "2018-09-05                                         0   \n",
       "2018-09-06                                         0   \n",
       "2018-09-07                                         0   \n",
       "\n",
       "            MX_Día del Trabajo [Labour Day] (Observed)  \n",
       "2018-09-03                                           0  \n",
       "2018-09-04                                           0  \n",
       "2018-09-05                                           0  \n",
       "2018-09-06                                           0  \n",
       "2018-09-07                                           0  \n",
       "\n",
       "[5 rows x 31 columns]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "c_holidays = CountryHolidays(countries=['US', 'MX'])\n",
    "periods = 365 * 5\n",
    "dates = pd.date_range(end='2023-09-01', periods=periods)\n",
    "holidays_df = c_holidays(dates)\n",
    "holidays_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c548b898-2f7e-4b11-8426-dd50ed68931c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# test shape of holidays_df\n",
    "assert len(holidays_df) == periods"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4aee4fca-68f0-4817-80c0-697b6d04120a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class SpecialDates:\n",
    "    \"\"\"Given a dictionary of categories and dates, returns a dataframe with the special dates.\"\"\"\n",
    "    \n",
    "    def __init__(self, special_dates: Dict[str, List[str]]):\n",
    "        self.special_dates = special_dates\n",
    "    \n",
    "    def __call__(self, dates: pd.DatetimeIndex):\n",
    "        total_special_dates = dict()\n",
    "        for key, val in self.special_dates.items():\n",
    "            date_vals = [ds.date() for ds in pd.to_datetime(val)]\n",
    "            total_special_dates[key] = [int(ds.date() in date_vals) for ds in dates]\n",
    "        return pd.DataFrame(total_special_dates, index=dates)\n",
    "    \n",
    "    def __name__(self):\n",
    "        return 'SpecialDates'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ef5f615-2d57-42bc-ace2-e3e77d82656d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "---\n",
       "\n",
       "#### SpecialDates\n",
       "\n",
       ">      SpecialDates (special_dates:Dict[str,List[str]])\n",
       "\n",
       "Given a dictionary of categories and dates, returns a dataframe with the special dates."
      ],
      "text/plain": [
       "---\n",
       "\n",
       "#### SpecialDates\n",
       "\n",
       ">      SpecialDates (special_dates:Dict[str,List[str]])\n",
       "\n",
       "Given a dictionary of categories and dates, returns a dataframe with the special dates."
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "show_doc(SpecialDates, title_level=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f967cda6-4958-4e03-93c9-d881ec3c2548",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Important Dates</th>\n",
       "      <th>Very Important Dates</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2018-09-03</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-09-04</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-09-05</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-09-06</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2018-09-07</th>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            Important Dates  Very Important Dates\n",
       "2018-09-03                0                     0\n",
       "2018-09-04                0                     0\n",
       "2018-09-05                0                     0\n",
       "2018-09-06                0                     0\n",
       "2018-09-07                0                     0"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "special_dates = SpecialDates(\n",
    "    special_dates={\n",
    "        'Important Dates': ['2021-02-26', '2020-02-26'],\n",
    "        'Very Important Dates': ['2021-01-26', '2020-01-26', '2019-01-26']\n",
    "    }\n",
    ")\n",
    "periods = 365 * 5\n",
    "dates = pd.date_range(end='2023-09-01', periods=periods)\n",
    "holidays_df = special_dates(dates)\n",
    "holidays_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de9f4656-d808-490f-8b1a-621396c3e7ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# test shape of holidays_df\n",
    "assert len(holidays_df) == periods\n",
    "assert holidays_df.sum().sum() == 5"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
